package io.renren.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.QpayConstants;
import io.renren.common.WxpayParam;
import io.renren.common.entity.*;
import io.renren.common.enums.CircleLevelEnum;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.controller.WxPayController;
import io.renren.dao.*;
import io.renren.dto.XlsShopOrdersDTO;
import io.renren.rabbitmq.MQSender;
import io.renren.service.*;
import io.renren.utils.AppResult;
import io.renren.utils.StringUtils;
import io.renren.utils.WXPayCommonUtil;
import net.sf.json.JSONObject;
import org.jdom2.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.*;

/**
 * 线上订单表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2020-04-12
 */
@Service
public class XlsShopOrdersServiceImpl extends CrudServiceImpl<XlsShopOrdersDao, XlsShopOrdersEntity, XlsShopOrdersDTO> implements XlsShopOrdersService {

    @Autowired
    private XlsShopOrdersDao xlsShopOrdersDao;
    @Autowired
    private XlsUserDao xlsUserDao;
    @Autowired
    private XlsUserService userService;
    @Autowired
    private XlsUsersAddressDao xlsUsersAddressDao;
    @Autowired
    private XlsCartDao xlsCartDao;
    @Autowired
    private XlsOrdersGoodsDao xlsOrdersGoodsDao;
    @Autowired
    private XlsCommodityDao xlsCommodityDao;
    @Autowired
    private MQSender mqSender;
    @Autowired
    private XlsUsersBankcardsDao xlsUsersBankcardsDao;
    @Autowired
    private XlsLogThirdpayService logThirdpayService;
    @Autowired
    private XlsLogCashService logCashService;
    @Autowired
    private XlsUpgradeAccountService xlsUpgradeAccountService;
    @Autowired
    private XlsUpgradeAccountDao xlsUpgradeAccountDao;

    @Override
    public QueryWrapper<XlsShopOrdersEntity> getWrapper(Map<String, Object> params) {
        String id = (String) params.get("id");

        QueryWrapper<XlsShopOrdersEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);

        return wrapper;
    }


    @Override
    @Transactional
    public AppResult addOrders(Long userId, String paramStr, Long userAddressId, Integer type) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            XlsUserEntity users = xlsUserDao.selectById(userId);
            if (StringUtils.isNull(users)) {
                return AppResult.ERROR("用户不存在请重新登录");
            }
            XlsUsersAddressEntity xlsUsersAddressEntity = xlsUsersAddressDao.selectById(userAddressId);
            if (StringUtils.isNull(xlsUsersAddressEntity)) {
                return AppResult.ERROR("请选择地址");
            }

            Map<String, Object> where = new HashMap<>();
            where.put("user_id", userId);
            where.put("is_check", 1);
            List<XlsCartEntity> cartList = xlsCartDao.selectByMap(where);
            if (cartList.isEmpty()) {
                return AppResult.ERROR("请选择要购买的商品");
            }
            List<Map<String, Object>> paramStrMap = JSON.parseObject(paramStr, new TypeReference<List<Map<String, Object>>>() {
            });
            if (!paramStrMap.isEmpty()) {
                BigDecimal goodsMoney = BigDecimal.ZERO;
                BigDecimal deliverMoney = BigDecimal.ZERO;
                //订单流水号
                String orderunique = StringUtils.getOrderIdByTime("L");
                //生成订单号
                String orderNo = StringUtils.getOrderIdByTime("D");
                XlsShopOrdersEntity shopOrders = new XlsShopOrdersEntity();
                shopOrders.setOrderNo(orderNo);
                shopOrders.setUserId(userId);
                shopOrders.setOrderStatus(-2);
                shopOrders.setIsClosed(-1);
                shopOrders.setIsPay(-1);
                shopOrders.setOrderType(1);
                xlsShopOrdersDao.addShopOrder(shopOrders);
                for (Map<String, Object> goodsMap : paramStrMap) {
                    String cartId = goodsMap.get("cartId").toString();
                    Long goodsId = Long.valueOf(goodsMap.get("goodsId").toString());
                    int cartNum = Integer.parseInt(goodsMap.get("cartNum").toString());
                    if (cartNum <= 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AppResult.ERROR("商品数量有误");
                    }
                    BigDecimal shopPrice = new BigDecimal(goodsMap.get("shopPrice").toString());
                    goodsMoney = goodsMoney.add(new BigDecimal(goodsMap.get("shopPrice").toString()).multiply(new BigDecimal(cartNum))).setScale(2, BigDecimal.ROUND_UP);
                    if (goodsMoney.compareTo(BigDecimal.ZERO) != 1) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AppResult.ERROR("商品金额错误");
                    }

                    XlsCommodityEntity xlsCommodityEntity = xlsCommodityDao.selectById(goodsId);
                    if (shopPrice.compareTo(new BigDecimal(xlsCommodityEntity.getShopPrice()).setScale(2,BigDecimal.ROUND_HALF_UP)) != 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AppResult.ERROR("商品金额错误");
                    }

                    /*生成ordergoods表*/
                    XlsOrdersGoodsEntity ordersGoods = new XlsOrdersGoodsEntity();
                    ordersGoods.setOrderId(shopOrders.getId());
                    ordersGoods.setGoodsId(goodsId);
                    ordersGoods.setGoodsNum(cartNum);
                    ordersGoods.setGoodsPrice(shopPrice);
                    ordersGoods.setCreateTime(new Date());
                    ordersGoods.setOrderType(shopOrders.getOrderType());
//							ordersGoodsList.add(ordersGoods);
                    xlsOrdersGoodsDao.insert(ordersGoods);
                    /*删除购物车内下单商品*/
                    xlsCartDao.deleteById(cartId);

                }
                BigDecimal totalMoney = goodsMoney.add(deliverMoney).setScale(2, BigDecimal.ROUND_UP);
                shopOrders.setGoodsMoney(goodsMoney);
                shopOrders.setTotalMoney(totalMoney);
                shopOrders.setOrderunique(orderunique);
                shopOrders.setUserAddressId(userAddressId);
                shopOrders.setCreateTime(new Date());
                xlsShopOrdersDao.updateById(shopOrders);

                /**
                 * 加入到RabbitMQ死信队列
                 */
                mqSender.sendDelay(orderunique);
                XlsUsersBankcardsEntity usersBankcards = new XlsUsersBankcardsEntity();
                usersBankcards.setUserId(userId);
                usersBankcards.setDataFlag(1);
                List<Map<String, Object>> usersBankcardsList = xlsUsersBankcardsDao.selectUsersBankcards(usersBankcards);
                resultMap.put("orderunique", orderunique);
                resultMap.put("usersBankcardsList", usersBankcardsList);
                return AppResult.OK("成功",resultMap);
            } else {
                TransactionAspectSupport.currentTransactionStatus().isRollbackOnly();
                return AppResult.ERROR("无订单");
            }

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AppResult.ERROR("下单失败");
        }

    }

    /**
     * 订单失效
     * @param orderunique
     * @return
     */
    @Override
    @Transactional
    public Map<String, Object> recoverGoodsNum(String orderunique) {
        Map<String,Object> resultMap=new HashMap<>();
        try{
            if (orderunique==null || "".equals(orderunique)){
                resultMap.put("code","500");
                resultMap.put("msg","没有对应订单");
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return resultMap;
            }
            XlsShopOrdersEntity shopOrders=new XlsShopOrdersEntity();
            shopOrders.setOrderunique(orderunique);
            List<XlsShopOrdersEntity> shopOrdersList = xlsShopOrdersDao.selectShopOrdersList(shopOrders);
            if (!shopOrdersList.isEmpty()){
                for (XlsShopOrdersEntity orders:shopOrdersList){
                    int orderStatus = orders.getOrderStatus();
                    if (orderStatus==-2){
                        Long orderId = orders.getId();
                        /*修改订单*/
                        orders.setOrderStatus(-5);//订单过期失效
                        xlsShopOrdersDao.updateById(orders);
                    }

                }
                resultMap.put("code","0");
                resultMap.put("msg","失效成功");
            }else{
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                resultMap.put("code","500");
                resultMap.put("msg","无订单");
            }
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            resultMap.put("code","500");
            resultMap.put("msg","订单设置失效和库存加回失败");
        }
        return resultMap;
    }

    /**
     * 第三方支付预下单
     * @param requestVX
     * @param orderunique
     * @param payType
     * @param bankCardId
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public AppResult thirdPayApply(HttpServletRequest requestVX, String orderunique, String payType, String bankCardId, String userId) {
        Map<String, Object> resultMap=new HashMap<>();
        try {
            if ("".equals(userId) || userId == null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AppResult.ERROR("您尚未登录，请重新登录");
            }
            XlsUserEntity users = xlsUserDao.selectById(Long.valueOf(userId));
            if (StringUtils.isNull(users)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AppResult.ERROR("您尚未登录，请重新登录");
            }
            if (orderunique == null || "".equals(orderunique)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AppResult.ERROR("请选择支付订单");
            }
            BigDecimal  totalCash = xlsShopOrdersDao.selectSumCashByOrderunique(orderunique);//订单支付金额
            XlsShopOrdersEntity shopOrders = new XlsShopOrdersEntity();
            shopOrders.setOrderunique(orderunique);
            List<XlsShopOrdersEntity> shopOrdersList = xlsShopOrdersDao.selectShopOrdersList(shopOrders);
            if (shopOrdersList.isEmpty()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AppResult.ERROR("没有可支付的订单");
            }

            for (XlsShopOrdersEntity orders : shopOrdersList) {
                Integer orderStatus = orders.getOrderStatus();
                if (orderStatus == -5) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AppResult.ERROR("订单过期失效");
                }
                orders.setPayType(Integer.parseInt(payType));
                int i = xlsShopOrdersDao.updateById(orders);
                if (i < 1) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AppResult.ERROR("订单状态修改有误");
                }
            }
            if ("2".equals(payType)){ //支付宝支付
                AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
                //将订单信息签名
                //实例化客户端
                AlipayClient alipayClient = new DefaultAlipayClient(QpayConstants.ALIPAY_GETEWAY, QpayConstants.ALI_APP_ID, QpayConstants.ALI_APP_PRIVATE_KEY, "json", QpayConstants.CHARSET, QpayConstants.ALIPAY_PUBLIC_KEY, "RSA2");
                //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
                AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
                //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
                model.setBody("购买商品");
                model.setSubject("众合商城");
                model.setOutTradeNo(orderunique);
                model.setTimeoutExpress("30m");
                model.setTotalAmount(totalCash.toString());
                model.setProductCode("QUICK_MSECURITY_PAY ");
                request.setBizModel(model);
                //   request.setNotifyUrl("http://"+notifyUrl+"/app/aliPay/payBack");
                request.setNotifyUrl(QpayConstants.ALIPAY_NOTIFYURL);
                String orderString = "";
                AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
                orderString = response.getBody();
                resultMap.put("orderString",orderString);
                resultMap.put("payType",payType);
                //插入第三方记录
                XlsLogThirdpayEntity newLogThirdpay=null;
                XlsLogThirdpayEntity logThirdpay=new XlsLogThirdpayEntity();
                logThirdpay.setOutTradeNo(orderunique);
                List<XlsLogThirdpayEntity> logThirdpays = logThirdpayService.selectLogThirdpayList(logThirdpay);
                if (logThirdpays.isEmpty()){
                    newLogThirdpay = logThirdpayService.initLogThirdpay(Long.valueOf(userId), "BUY_GOODS", 2, QpayConstants.SYB_CUSID,
                            totalCash, orderunique, model.toString(), 1, "购物支付宝支付申请");
                    int insert = logThirdpayService.insertThirdpay(newLogThirdpay);
                }else {
                    newLogThirdpay=logThirdpays.get(0);
                }
                newLogThirdpay.setResponse(orderString);
                newLogThirdpay.setResponseTime(new Date());
                logThirdpayService.updateById(newLogThirdpay);
                return AppResult.OK(resultMap);
            }
            if ("1".equals(payType)){
                WxpayParam wxpayParam = new WxpayParam();
                wxpayParam.setTotalPrice(xlsShopOrdersDao.selectSumCashByOrderunique(orderunique));
                wxpayParam.setOutTradeNo(orderunique);
                wxpayParam.setBody("众合商城商品购买");
                Map<String, String> stringStringMap = WxPayController.wxPayFunction(requestVX, wxpayParam);
                /**插入第三方*/
                XlsLogThirdpayEntity newLogThirdpay=null;
                XlsLogThirdpayEntity logThirdpay=new XlsLogThirdpayEntity();
                logThirdpay.setOutTradeNo(orderunique);
                List<XlsLogThirdpayEntity> logThirdpays = logThirdpayService.selectLogThirdpayList(logThirdpay);
                if (logThirdpays.isEmpty()){
                    newLogThirdpay = logThirdpayService.initLogThirdpay(Long.valueOf(userId), "BUY_GOODS", 1, QpayConstants.WX_MCH_ID,
                            wxpayParam.getTotalPrice(), orderunique, stringStringMap.toString(), 1, "购物微信申请");
                    int i = logThirdpayService.insertThirdpay(newLogThirdpay);
                }else {
                    newLogThirdpay=logThirdpays.get(0);
                }
                JSONObject jsonObject = JSONObject.fromObject(stringStringMap);
                newLogThirdpay.setResponse(stringStringMap.toString());
                newLogThirdpay.setResponseTime(new Date());
                logThirdpayService.updateById(newLogThirdpay);
                resultMap.put("code","1");
                resultMap.put("orderString", jsonObject);
                resultMap.put("msg","预下单成功");
                resultMap.put("payType",payType);
                return AppResult.OK(resultMap);
            }
        }catch (Exception e){
            e.printStackTrace();
            resultMap.put("msg","服务器错误");
            AppResult.ERROR("服务器错误");
        }
        resultMap.put("msg","预下单失败");
        return AppResult.ERROR("预下单失败");
    }

    @Override
    @Transactional
    public AppResult aliPayBack(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> params = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        Map<String, Object> payBackMap = aliPayBack(params);
        if("0".equals(payBackMap.get("code").toString())){
            try {
                response.getWriter().print("success");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return AppResult.OK(payBackMap);
        }else {
            return AppResult.ERROR(payBackMap.get("msg").toString());
        }
    }

    /**
     * 微信支付逻辑
     * @param request
     * @param response
     */
    @Override
    @Transactional
    public void wxPayBack(HttpServletRequest request, HttpServletResponse response) {
        String returnStr = "";
        Map<String, String> params = null;
        InputStream inputStream = null;
        ByteArrayOutputStream outputSteam = null;
        try {
            inputStream = request.getInputStream();
            outputSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                outputSteam.write(buffer, 0, len);
            }
            String resultxml = new String(outputSteam.toByteArray(), "utf-8");

            params = WXPayCommonUtil.doXMLParse(resultxml);
            boolean b = wxPayBackLogic(params);
            if (b) {
                response.getWriter().print("success");
                returnStr = WXPayCommonUtil.getXML("SUCCESS", "");
            } else {
                //return AjaxResult.error(payBackMap.get("msg").toString());
                returnStr = WXPayCommonUtil.getXML("FAIL", "微信支付失败");
            }
        } catch (JDOMException | IOException e) {
            e.printStackTrace();
            returnStr = WXPayCommonUtil.getXML("FAIL", "微信支付失败");
        }
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        pw.write(returnStr);
        pw.flush();
        pw.close();
    }

    @Override
    public AppResult getAllOrderData(Integer pageNum, Long userId, String orderStatus) {
        List<Map<String, Object>>  resultList=new ArrayList<>();
        Map<String,Object> resultMap =new HashMap<>();
        XlsUserEntity users = xlsUserDao.selectById(userId);
        if (StringUtils.isNull(users)){
            return AppResult.ERROR("无效用户");
        }
        XlsShopOrdersEntity shopOrders=new XlsShopOrdersEntity();
        shopOrders.setUserId(userId);
        if (orderStatus!=null && !"".equals(orderStatus)){
            shopOrders.setOrderStatus(Integer.parseInt(orderStatus));
        }
        List<Map<String,Object>> shopOrdersList = xlsShopOrdersDao.selectShopOrdersInfoList(shopOrders);
        if (shopOrdersList.isEmpty()){
            return AppResult.OK("没有记录");
        }
        resultMap.put("shopOrdersList",shopOrdersList);
        resultMap.put("orderType",1);
        resultList.add(resultMap);
        Map<String,Object> map=new HashMap<>();
        map.put("data",resultList);
        return AppResult.OK(map);
    }

    @Override
    public AppResult updateOrderStatus(XlsShopOrdersEntity shopOrders) {
        int i = xlsShopOrdersDao.updateById(shopOrders);
        if (i == 1) {
            return AppResult.OK("订单操作成功");
        } else {
            return AppResult.OK("订单操作失败");
        }
    }


    /**
     * 支付宝回调
     * @param params
     * @return
     */
    @Transactional
    public Map<String, Object> aliPayBack(Map<String, String> params) {
        Map<String, Object> resultMap=new HashMap<>();
        try {

            boolean flag = AlipaySignature.rsaCheckV1(params, QpayConstants.ALIPAY_PUBLIC_KEY, QpayConstants.CHARSET, "RSA2");
            if(!flag){
                resultMap.put("code","500");
                resultMap.put("msg","验签失败");
                return resultMap;
            }else {
                String trade_status = params.get("trade_status");
                String	out_trade_no = params.get("out_trade_no");
                XlsShopOrdersEntity shopOrders = new XlsShopOrdersEntity();
                shopOrders.setOrderunique(out_trade_no);
                shopOrders.setOrderStatus(-2);
                List<XlsShopOrdersEntity> shopOrdersList = xlsShopOrdersDao.selectShopOrdersList(shopOrders);
                if (shopOrdersList.isEmpty()) {
                    resultMap.put("code", "500");
                    resultMap.put("msg", "没有可支付的订单");
                    return resultMap;
                }if(shopOrdersList.get(0).getPayType()!=2) {
                    XlsShopOrdersEntity shopOrderses = shopOrdersList.get(0);
                    shopOrderses.setPayType(2);
                    shopOrders.setOrderStatus(0);
                    xlsShopOrdersDao.updateById(shopOrderses);
                }
                //更新第三方记录
                XlsLogThirdpayEntity newLogThirdpay=null;
                XlsLogThirdpayEntity logThirdpay=new XlsLogThirdpayEntity();
                logThirdpay.setOutTradeNo(out_trade_no);
                List<XlsLogThirdpayEntity> logThirdpays = logThirdpayService.selectLogThirdpayList(logThirdpay);
                if (!logThirdpays.isEmpty()){
                    newLogThirdpay=logThirdpays.get(0);
                }
                if (trade_status.equals("TRADE_SUCCESS")) {
                    if (flag){
                        newLogThirdpay.setPayStatus(3);
                        newLogThirdpay.setRequest("trade_status:"+trade_status);
                        newLogThirdpay.setResponse("支付宝SUCCESS");
                        newLogThirdpay.setPayType(2);
                        newLogThirdpay.setRemark("支付宝回调成功");
                    }else {
//						newLogThirdpay.setRequest("FAIL");
                        newLogThirdpay.setRequest("trade_status:"+trade_status);
                        newLogThirdpay.setResponse("支付宝SUCCESS");
                        newLogThirdpay.setPayType(2);
                        newLogThirdpay.setPayStatus(4);
                        newLogThirdpay.setRemark("支付宝回调结果失败");
                    }
                }else {
//					newLogThirdpay.setRequest("FAIL");
                    newLogThirdpay.setRequest("trade_status:"+trade_status);
                    newLogThirdpay.setResponse("支付宝SUCCESS");
                    newLogThirdpay.setPayType(2);
                    newLogThirdpay.setPayStatus(4);
                    newLogThirdpay.setRemark("支付宝回调状态失败");
                }
                logThirdpayService.updateById(newLogThirdpay);
//				String trxamt = params.get("trxamt");//交易金额
                String totalAmount = params.get("total_amount");
                BigDecimal totalCash= new BigDecimal(totalAmount);
                Map<String, Object> map = callBack(out_trade_no, totalCash);
                if ("500".equals(map.get("code").toString())){
//				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    resultMap.put("code","500");
                    resultMap.put("msg","回调处理失败");
                    return resultMap;
                }
                resultMap.put("code","0");
                resultMap.put("msg","回调处理成功");
                return resultMap;
            }

        }catch (Exception e){
//			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            resultMap.put("code","500");
            resultMap.put("msg","回调处理失败");
            return resultMap;
        }

    }

    /**
     * 微信回调
     * @param params
     * @return
     */
    @Transactional
    public boolean wxPayBackLogic(Map<String, String> params) {
        System.out.println("进入微信回调接口--------");
        try {
            boolean flag = WXPayCommonUtil.isTenpaySigns(params);
            System.out.println(flag+"回来的数据");
            if(!flag){
                return  false;
            }else {
                String return_code = params.get("return_code");
                String result_code = params.get("result_code");
                String	out_trade_no = params.get("out_trade_no");
                XlsShopOrdersEntity shopOrders = new XlsShopOrdersEntity();
                shopOrders.setOrderunique(out_trade_no);
                shopOrders.setOrderStatus(-2);
                List<XlsShopOrdersEntity> shopOrdersList = xlsShopOrdersDao.selectShopOrdersList(shopOrders);
                if (shopOrdersList.isEmpty()) {
                    return  false;
                }if(shopOrdersList.get(0).getPayType()!=1) {
                    XlsShopOrdersEntity shopOrderses = shopOrdersList.get(0);
                    shopOrderses.setPayType(1);
                    shopOrders.setOrderStatus(0);
                    xlsShopOrdersDao.updateById(shopOrderses);
                }
                //更新第三方记录
                XlsLogThirdpayEntity newLogThirdpay=null;
                XlsLogThirdpayEntity logThirdpay=new XlsLogThirdpayEntity();
                logThirdpay.setOutTradeNo(out_trade_no);
                List<XlsLogThirdpayEntity> logThirdpays = logThirdpayService.selectLogThirdpayList(logThirdpay);
                if (!logThirdpays.isEmpty()){
                    newLogThirdpay=logThirdpays.get(0);
                }
                if (return_code.equals("SUCCESS")&&result_code.equals("SUCCESS")) {
                    if (flag){
                        newLogThirdpay.setRequest("return_code:"+return_code+",result_code:"+result_code);
                        newLogThirdpay.setResponse("微信SUCCESS");
                        newLogThirdpay.setPayStatus(3);
                        newLogThirdpay.setPayType(1);
//						newLogThirdpay.setRequest("SUCCESS");
                        newLogThirdpay.setRemark("微信回调成功");
                    }else {
                        newLogThirdpay.setRequest("return_code:"+return_code+",result_code:"+result_code);
                        newLogThirdpay.setResponse("微信SUCCESS");
//						newLogThirdpay.setRequest("FAIL");
                        newLogThirdpay.setPayStatus(4);
                        newLogThirdpay.setPayType(1);
                        newLogThirdpay.setRemark("微信回调结果失败");
                    }
                }else {
                    newLogThirdpay.setRequest("return_code:"+return_code+",result_code:"+result_code);
                    newLogThirdpay.setResponse("微信SUCCESS");
//					newLogThirdpay.setRequest("FAIL");
                    newLogThirdpay.setPayStatus(4);
                    newLogThirdpay.setPayType(1);
                    newLogThirdpay.setRemark("微信回调状态失败");
                }
                logThirdpayService.updateById(newLogThirdpay);
//				String trxamt = params.get("trxamt");//交易金额
                String totalAmount = params.get("total_fee");
                BigDecimal totalCash= new BigDecimal(totalAmount);
                Map<String, Object> map = callBack(out_trade_no, totalCash);
                if ("500".equals(map.get("code").toString())){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                }
                return  true;
            }

        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }


    /**
     * 支付回调逻辑
     * @param orderunique
     * @param totalCash 支付回调的支付金额
     * @return
     */
    @Transactional
    public Map<String,Object> callBack(String orderunique,BigDecimal totalCash) {
        Map<String,Object> resultMap=new HashMap<>();
        try{
            XlsShopOrdersEntity shopOrders = new XlsShopOrdersEntity();
            shopOrders.setOrderunique(orderunique);
            shopOrders.setOrderStatus(-2);
            List<XlsShopOrdersEntity> shopOrdersList = xlsShopOrdersDao.selectShopOrdersList(shopOrders);
            if (shopOrdersList.isEmpty()) {
                resultMap.put("code", "500");
                resultMap.put("msg", "没有可支付的订单");
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return resultMap;
            }
            BigDecimal  amount = xlsShopOrdersDao.selectSumCashByOrderunique(orderunique);//订单支付金额
            XlsShopOrdersEntity shopOrders1 = shopOrdersList.get(0);
            int payType = shopOrders1.getPayType();
            BigDecimal  amountMoney=BigDecimal.ZERO;
            //银联
//            if (payType==3){
//                amountMoney=amount.multiply(new BigDecimal(100)).setScale(0);
//            }
            if (payType==2){
                amountMoney=amount;
            }
            if (payType==1){
                amountMoney=amount.multiply(new BigDecimal(100)).setScale(0);
                System.out.println(amountMoney+",对比"+totalCash);
            }
            if (totalCash.compareTo(amountMoney)!=0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                resultMap.put("code","500");
                resultMap.put("msg","支付金额与订单金额不符");
                return resultMap;
            }
            for (XlsShopOrdersEntity orders : shopOrdersList) {
                XlsOrdersGoodsEntity ordersGoods=new XlsOrdersGoodsEntity();
                ordersGoods.setOrderId(orders.getId());
                /*修改明细订单*/
                List<XlsOrdersGoodsEntity> ordersGoodsList = xlsOrdersGoodsDao.selectOrdersGoodsList(ordersGoods);
                orders.setOrderStatus(0);
                orders.setIsPay(1);
                orders.setPaymentTime(new Date());
                int i = xlsShopOrdersDao.updateById(orders);
            }
            Long userId = shopOrdersList.get(0).getUserId();
            //更新第三方记录
            XlsLogThirdpayEntity newLogThirdpay=null;
            XlsLogThirdpayEntity logThirdpay=new XlsLogThirdpayEntity();
            logThirdpay.setOutTradeNo(orderunique);
            List<XlsLogThirdpayEntity> logThirdpays = logThirdpayService.selectLogThirdpayList(logThirdpay);
            if (!logThirdpays.isEmpty()){
                newLogThirdpay=logThirdpays.get(0);
                newLogThirdpay.setPayStatus(3);
                newLogThirdpay.setRemark("支付完成");
                logThirdpayService.updateById(newLogThirdpay);
            }
            /*插入现金流水*/
            XlsLogCashEntity logCash = logCashService.intiLogCash(1, userId, Long.valueOf(1), orderunique, BigDecimal.ZERO, -1, amount.setScale(2,BigDecimal.ROUND_HALF_UP), "消费");
            logCashService.insert(logCash);
            XlsUpgradeAccountEntity upgradeAccounts=xlsUpgradeAccountService.selectByUserId(userId);
            XlsUserEntity xlsUserEntity = xlsUserDao.selectById(userId);
            if ((upgradeAccounts.getAccCash().add(amount)).compareTo(new BigDecimal(3000))>-1 && xlsUserEntity.getCircleLevel()==5){
                xlsUserEntity.setCircleLevel(CircleLevelEnum.PRIMARY_LEVEL.value());
                xlsUserDao.updateById(xlsUserEntity);
                upgradeAccounts.setTotalCash((upgradeAccounts.getTotalCash().add(amount)).setScale(2,BigDecimal.ROUND_HALF_UP));
                upgradeAccounts.setAccCash(BigDecimal.ZERO);
                int i = xlsUpgradeAccountDao.updateById(upgradeAccounts);
                if (i<1){
                    TransactionAspectSupport.currentTransactionStatus().isRollbackOnly();
                    resultMap.put("code","500");
                    resultMap.put("msg","业务处理失败");
                    return resultMap;
                }
                userService.insertOrUpdateXlsCirclePri(xlsUserEntity);
            }else {
                XlsUpgradeAccountEntity upgradeAccount=new XlsUpgradeAccountEntity();
                upgradeAccount.setUserId(userId);
                upgradeAccount.setAccCash(amount);
                int i=xlsUpgradeAccountService.updateUpgradeAccountByUserId(upgradeAccount);
                if (i<1){
                    TransactionAspectSupport.currentTransactionStatus().isRollbackOnly();
                    resultMap.put("code","500");
                    resultMap.put("msg","业务处理失败");
                    return resultMap;
                }
            }

            resultMap.put("code","0");
            resultMap.put("msg","业务处理完成");
            return resultMap;
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            resultMap.put("code","500");
            resultMap.put("msg","业务处理失败");
            return resultMap;
        }
    }





}